package bz.ziro.kanbe.controller.mng.browser;

import java.util.Date;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import bz.ziro.kanbe.logic.TemplateLogic;
import bz.ziro.kanbe.model.TemplateBrowser;
import bz.ziro.kanbe.util.KeyFactory;

/**
 * ブラウザデータの追加
 * @author Administrator
 *
 */
public class AddController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(AddController.class.getName());

    @Override
    public Navigation run() {

        //サイトのキーを取得
        String siteKeyBuf = sessionScope("siteKey");
        String templateKeyBuf = (String)requestScope("tempKey");
        String agentKeyBuf = (String)requestScope("agKey");

        //キーの作成
        Key templateKey = KeyFactory.createTemplateKey(Long.valueOf(siteKeyBuf),Long.valueOf(templateKeyBuf));
        Key agentKey = KeyFactory.createAgentKey(Long.valueOf(agentKeyBuf));

        TemplateBrowser browser = new TemplateBrowser();
        BeanUtil.copy(request, browser);

        //テンプレートをコンパイル
        String rtn = TemplateLogic.compile(browser.getTemplateData());
        if ( rtn != null ) {
        	requestScope("message",rtn);
        	return forward("message.jsp");
        }
        //キーを設定
        Key key = KeyFactory.allocateBrowserKey(templateKey);
        browser.setKey(key);
        browser.setTemplateKey(templateKey);
        browser.setAgentKey(agentKey);

        //作成者情報を登録
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        browser.setCreator(user);
        browser.setCreateDate(new Date());

        Datastore.put(browser);
        return forward("../message.jsp");
    }
}
